<template>
    <div class="detail-main">
        <div class="content">
            <div class="tips-info">
                <div class="tip-item" @click="guideHandler(1)">
                    <img class="tip-icon" src="@/assets/channelConfig/marketingApplet/tip.png" />
                    <span>怎么修改小程序基本信息？</span>
                </div>
                <div class="tip-item" @click="guideHandler(2)">
                    <img class="tip-icon" src="@/assets/channelConfig/marketingApplet/tip.png" />
                    <span>怎么解除授权小程序？</span>
                </div>
                <div class="tip-item" @click="guideHandler(3)">
                    <img class="tip-icon" src="@/assets/channelConfig/marketingApplet/tip.png" />
                    <span>怎么设置小程序登录邮箱和密码？</span>
                </div>
            </div>
            <div class="box-info">
                <div class="title"><span></span>基本信息</div>
                <div class="info">
                    <span class="label">APPID（小程序ID）：</span>
                    <div>{{ baseInfo.appid }}</div>
                    <span class="copybtn" @click="copyHandler">复制</span>
                </div>
                <div class="info">
                    <span class="label">原始ID：</span>
                    <div>{{ showFiledValueHandler(baseInfo.user_name) }}</div>
                </div>
                <div class="info">
                    <span class="label">小程序名称：</span>
                    <div>{{ showFiledValueHandler(baseInfo.nick_name) }}</div>
                </div>
                <div class="info">
                    <span class="logo label">小程序头像：</span>
                    <div>
                        <el-avatar :size="64" :src="baseInfo.head_image"> </el-avatar>
                    </div>
                </div>
                <div class="info">
                    <span class="label">小程序介绍：</span>
                    <div class="group">
                        <span>{{ showFiledValueHandler(baseInfo.signature) }}</span>
                        <span v-if="!baseInfo.signature" class="copybtn" @click="guideHandler(1)">去完善</span>
                    </div>
                </div>
                <div class="info">
                    <span class="label">服务类目：</span>
                    <div v-if="baseInfo.categories.length === 0" class="group">
                        <span>-</span>
                        <span class="copybtn" @click="guideHandler(1)">去完善</span>
                    </div>
                    <div v-else>
                        <div v-for="(item, idx) in baseInfo.categories" :key="idx">
                            {{ item.first_name }}/{{ item.second_name }}
                        </div>
                    </div>
                </div>
                <div class="info">
                    <span class="label">主体信息：</span>
                    <div>{{ baseInfo.principal_name }}</div>
                </div>
                <div class="info">
                    <span class="logo label">小程序码：</span>
                    <div class="group">
                        <el-avatar :size="64" :src="baseInfo.miniapp_url"> </el-avatar>
                        <span
                            v-if="baseInfo.miniapp_url"
                            class="copybtn"
                            @click="downloadHandler(baseInfo.miniapp_url, baseInfo.nick_name)">
                            下载
                        </span>
                    </div>
                </div>
                <div class="info">
                    <span class="label">小程序介绍页：</span>
                    <div class="group">
                        <span>{{ baseInfo.miniapp_custom_url ? '已配置' : '-' }}</span>
                        <span class="copybtn" @click="introductionHandler">{{
                            baseInfo.miniapp_custom_url ? '修改配置' : '去配置'
                        }}</span>
                    </div>
                </div>
                <div class="title"><span></span>版本信息</div>
                <div class="infoWrap">
                    <div class="info">
                        <span class="label">正式版本：</span>
                        <div class="current">
                            <span v-if="versionInfo.current_version">{{ versionInfo.current_version }}</span>
                            <span v-if="!versionInfo.current_version" class="nopub">尚未发布</span>
                            <span v-if="isShowDom1" class="nopub mr10"> (当前版本已经是最新版本) </span>
                            <div class="exam">
                                <span v-if="isShowDom2" class="mr10" @click="commitHandler"> 提交审核 </span>
                                <el-tooltip
                                    v-if="versionInfo.can_commit === 2"
                                    effect="dark"
                                    content="小程序基本信息尚未完善，无法提交审核"
                                    placement="top">
                                    <span class="disabled">提交审核</span>
                                </el-tooltip>
                            </div>
                            <div v-if="isShowDom3" class="exam mr10">
                                <span @click="commitHandler(3)">升级</span>
                            </div>
                        </div>
                    </div>
                    <div class="info">
                        <span class="label">更新时间：</span>
                        <span>{{ showFiledValueHandler(versionInfo.update_time) }}</span>
                    </div>
                    <div class="info">
                        <span class="label">更新状态：</span>
                        <div class="value">
                            <div class="update-status">
                                <span>{{ showFiledValueHandler(versionInfo.current_version_status_desc) }}</span>
                                <div v-if="versionInfo.current_version_status === 3" class="exam mr10">
                                    <span @click="commitHandler(1)">重新提交审核</span>
                                </div>
                                <div v-if="versionInfo.current_version_status === 4" class="exam mr10">
                                    <span @click="commitHandler(2)">重新发布</span>
                                </div>
                                <div v-if="versionInfo.can_cancel === 1" class="exam">
                                    <span class="mr10" @click="cancelCommitHandler">取消升级</span>
                                </div>
                            </div>
                            <div v-if="versionInfo.fail_reason" class="fail-reason">
                                <span>失败原因：</span>
                                <span class="mr10">{{ versionInfo.fail_reason }}</span>
                                <span v-if="versionInfo.code === 2005012" class="exam" @click="guideHandler(4)">
                                    开通接口权限
                                </span>
                                <span v-if="versionInfo.code === 2005013" class="exam" @click="guideHandler(5)">
                                    配置服务器域名
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="info">
                        <span class="label">最新版本：</span>
                        <span>{{ showFiledValueHandler(versionInfo.last_version) }}</span>
                        <el-popover
                            placement="bottom"
                            :title="`${versionInfo.last_version}版本说明`"
                            :width="200"
                            trigger="click"
                            :content="versionInfo.last_version_desc">
                            <template #reference>
                                <span class="exam mr10">版本说明</span>
                            </template>
                        </el-popover>
                    </div>
                    <div class="info">
                        <span class="label">体验二维码：</span>
                        <div class="exam">
                            <div>
                                <el-tooltip
                                    v-if="experienceUrlFlag"
                                    effect="dark"
                                    content="暂无小程序版本，无法生成小程序二维码"
                                    placement="top">
                                    <span>生成体验二维码</span>
                                </el-tooltip>
                                <span v-else @click="showQrHandler">生成体验二维码</span>
                            </div>
                            <span class="nopub mt10 f11">微信扫描体验二维码体验最新版小程序</span>
                        </div>
                    </div>
                    <div v-if="versionInfo.current_version" class="info">
                        <span class="label">关联企业微信：</span>
                        <span class="value">若需要在企业微信中打开此小程序，需先关联企业微信</span>
                        <span class="exam mr10" @click="onAssociated">如何关联？</span>
                    </div>
                </div>
            </div>
        </div>
        <el-dialog v-model="qrShow" width="30%">
            <template #header>
                <span>小程序体验二维码</span>
            </template>
            <template #default>
                <div class="qrdiv">
                    <img :src="experience_url" />
                </div>
            </template>
            <template #footer>
                <el-button type="primary" @click="downloadHandler(experience_url, baseInfo.nick_name)">下载</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
    getMiniAppInfo,
    miniAppRecommit,
    miniAppApplyCancel,
    miniAppExperienceUrl
} from '@/api/channelconfig/marketingApplet';
import useClipboard from 'vue-clipboard3';

const { toClipboard } = useClipboard();
const router = useRouter();
const route = useRoute();

const baseInfo = reactive<any>({
    appid: '',
    principal_name: '',
    categories: [],
    current_version: '',
    commitStatusDesc: '',
    defaultPayCode: ''
});

const versionInfo = reactive<any>({});

const qrShow = ref(false);

const experience_url = ref('');

const experienceUrlFlag = ref<boolean>(false);

const isShowDom1 = computed(() => {
    return versionInfo.current_version && versionInfo.current_version == versionInfo.last_version;
});

const isShowDom2 = computed(() => {
    return (
        versionInfo.can_commit === 1 &&
        versionInfo.current_version_status != 3 &&
        versionInfo.current_version_status != 4 &&
        !versionInfo.current_version
    );
});

const isShowDom3 = computed(() => {
    return (
        versionInfo.can_commit === 1 &&
        versionInfo.current_version_status != 3 &&
        versionInfo.current_version_status != 4 &&
        versionInfo.current_version
    );
});

const guideHandler = (type?: any) => {
    if (type == 3) {
        window.open('https://developers.weixin.qq.com/community/develop/doc/000c4c6ffb43f809859a0da4456001');
    } else {
        window.open(`/perfect-info-guide?type=${type}`);
    }
};

const onAssociated = () => {
    window.open('/associated-applet');
};

const introductionHandler = () => {
    router.push({
        path: '/channelconfig/qywechat/marketingApplet/introduction',
        query: {
            id: route.query.id,
            type: baseInfo.mini_program_type
        }
    });
};

const copyHandler = async () => {
    try {
        await toClipboard(baseInfo.appid);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const showFiledValueHandler = (val?: any) => {
    return val ? val : '-';
};

const downloadHandler = (imgUrl?: any, name?: any) => {
    const a = document.createElement('a');
    fetch(imgUrl)
        .then(res => res.blob())
        .then(blob => {
            a.href = URL.createObjectURL(blob);
            a.download = name;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(a.href);
            document.body.removeChild(a);
        });
};

const commitHandler = async (type?: any) => {
    let text = '提交审核';
    if (type == 1) {
        text = '重新提交审核';
    } else if (type == 2) {
        text = '重新发布';
    } else if (type == 3) {
        text = '升级';
    }
    const flag = await ElMessageBox.confirm(`你确定要${text}吗？`, '注意！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).catch(err => {});
    if (flag) {
        const isSuccess = await miniAppRecommit({ id: route.query.id }).catch((err: any) => {
            ElMessage.error(err);
        });
        if (isSuccess) {
            ElMessage.success('操作成功！');
            queryAppInfo();
        }
    }
};

const cancelCommitHandler = async () => {
    const flag = await ElMessageBox.confirm('你确定要取消升级吗？', '注意！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).catch(err => {});
    if (flag) {
        const isSuccess = await miniAppApplyCancel({ id: route.query.id }).catch((err: any) => {
            ElMessage.error(err);
        });
        if (isSuccess) {
            ElMessage.success('操作成功！');
            queryAppInfo();
        }
    }
};

const showQrHandler = async () => {
    if (experienceUrlFlag.value) return;
    if (experience_url.value) {
        qrShow.value = true;
        return;
    }
    const data = await miniAppExperienceUrl({ id: route.query.id });
    if (!data.experience_url) {
        experienceUrlFlag.value = true;
        return;
    }
    experience_url.value = data.experience_url;
    qrShow.value = true;
};

const queryAppInfo = async () => {
    const res = await getMiniAppInfo({ id: route.query.id });
    Object.assign(baseInfo, res.base_info);
    Object.assign(versionInfo, res.version_info);
    baseInfo.categories = (res.base_info && res.base_info.categories) || [];
};

onMounted(() => {
    queryAppInfo();
});
</script>
<style lang="scss" scoped>
.detail-main {
    padding: 24px;
    background: #ffffff;
    position: relative;
    .content {
        .tips-info {
            position: absolute;
            top: 25px;
            right: 0;
            .tip-item {
                display: flex;
                align-items: center;
                flex-direction: row;
                margin-bottom: 10px;
                cursor: pointer;
                color: var(--el-color-primary);
                font-size: 14px;
                .tip-icon {
                    width: 20px;
                    height: 20px;
                    margin-right: 5px;
                }
            }
        }
        .box-info {
            .title {
                display: flex;
                align-items: center;
                margin-bottom: 16px;
                color: #33302d;
                font-size: 16px;
                font-weight: 700;
                line-height: 18px;
                span {
                    width: 4px;
                    height: 16px;
                    margin-right: 8px;
                    background: var(--el-color-primary);
                }
            }
            .info {
                display: flex;
                margin-bottom: 16px;
                color: #33302d;
                font-size: 14px;
                font-weight: 400;
                line-height: 20px;
                .label {
                    min-width: 150px;
                    margin-right: 15px;
                    text-align: right;
                    font-weight: 500;
                }
                .value {
                    display: flex;
                    align-items: flex-start;
                    flex-direction: column;
                    .update-status {
                        display: flex;
                        flex-direction: row;
                    }
                    .fail-reason {
                        margin-top: 10px;
                        color: var(--el-color-error);
                    }
                }
                .copybtn {
                    margin-left: 10px;
                    cursor: pointer;
                    color: var(--el-color-primary);
                    font-size: 14px;
                }
                .disabled {
                    cursor: not-allowed;
                    color: var(--el-color-primary-light-5);
                }
                .logo {
                    line-height: 64px;
                }
                .group {
                    display: flex;
                    align-items: center;
                    flex-direction: row;
                }
                .current {
                    display: flex;
                    flex-direction: row;
                }
                .nopub {
                    display: inline-block;
                    margin-right: 10px;
                    color: #999;
                }
                .exam {
                    cursor: pointer;
                    color: var(--el-color-primary);
                    font-size: 14px;
                    font-weight: 400;
                    line-height: 20px;
                }
                .mr10 {
                    margin-left: 10px;
                }
                .auth {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 64px;
                    height: 22px;
                    color: #ffb949;
                    border-radius: 2px;
                    background: #fff7ea;
                    img {
                        width: 14px;
                        height: 14px;
                        margin-right: 4px;
                    }
                }
            }
        }
    }
    .qrdiv {
        padding-bottom: 24px;
        text-align: center;
        img {
            width: 60%;
        }
    }
}
</style>
